package com.tfb.web.controller;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.tlr.device.rest.AppContext;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println("Only support post method for file upload!");
    }
    private String getPeerSyncAddress() throws FileNotFoundException, IOException
    {
        String propFile = AppContext.getPeerSyncAddress();
        try (InputStream in = new FileInputStream(new File(propFile))) {
            Properties props = new Properties();
            props.load(in);
            return props.getProperty("peer_sync_address");
        }
       // http://192.168.1.55:8080/TianLeRong/UploadServlet
    }
    private void syncToPeer(String assessmentid, String fileName, String strPath) {
        try {
            // http://192.168.1.55:8080/TianLeRong/device/rest/health_device/notify
            String strPeerAddrss = getPeerSyncAddress();
            String strUrl = strPeerAddrss + "/" + assessmentid;
            String filePath = strPath + "/" + fileName;
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty("FileName", fileName);
            // connection.setRequestProperty("content-type", "text/html");
            BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());

            // ��ȡ�ļ��ϴ���������
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int numReadByte = 0;
            while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
                out.write(bytes, 0, numReadByte);
            }

            out.flush();
            fileInputStream.close();
            // ��ȡURLConnection����Ӧ
            DataInputStream in = new DataInputStream(connection.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void writeFile(HttpServletRequest request, String savePath) {
        try {
            String filename = request.getHeader("FileName");

            InputStream in = request.getInputStream();

            FileOutputStream out = new FileOutputStream(savePath + "/" + filename);

            byte buffer[] = new byte[1024];

            int len = 0;

            while ((len = in.read(buffer)) > 0) {

                out.write(buffer, 0, len);
            }

            in.close();

            out.close();
        } catch (Exception e) {
            // message= "fail to upload file due to:"+e.toString();
            e.printStackTrace();

        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String strPath = request.getPathInfo();
        int nLastPos = strPath.lastIndexOf("/");
        String strAssessment = strPath.substring(nLastPos + 1);

        String savePath = AppContext.getFileUploadPath() + "/" + strAssessment;
        File file = new File(savePath);

        if (!file.exists() && !file.isDirectory()) {
            System.out.println(savePath + " is not existing!");
            file.mkdir();
        }

        String message = "";
        try {

            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            if (!ServletFileUpload.isMultipartContent(request)) {

                writeFile(request, savePath);
                response.getWriter().println("peer server sync file done!");
                return;
            }

            List<FileItem> list = upload.parseRequest(request);
            for (FileItem item : list) {
                if (item.isFormField()) {
                    String name = item.getFieldName();

                    String value = item.getString("UTF-8");

                    System.out.println(name + "=" + value);
                } else {
                    String filename = item.getName();
                    System.out.println("upload file:" + filename);
                    if (filename == null || filename.trim().equals("")) {
                        continue;
                    }

                    filename = filename.substring(filename.lastIndexOf("/") + 1);

                    InputStream in = item.getInputStream();

                    FileOutputStream out = new FileOutputStream(savePath + "/" + filename);

                    byte buffer[] = new byte[1024];

                    int len = 0;

                    while ((len = in.read(buffer)) > 0) {

                        out.write(buffer, 0, len);
                    }

                    in.close();

                    out.close();
                    syncToPeer(strAssessment,  filename,  savePath);
                    item.delete();

                }
            }
        } catch (Exception e) {
            message = "fail to upload file due to:" + e.toString();
            e.printStackTrace();

        }
        response.getWriter().println("done");
    }

}
